package com.gitee.feizns.explore.data_structure.visual.frame;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.awt.*;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

/**
 * @author feizns
 * @since 2020/1/2
 */
public abstract class Utils {

    public static Graphics2D init(Graphics g) {
        Graphics2D ret = (Graphics2D) g;
        //抗锯齿
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        ret.addRenderingHints(hints);
        return ret;
    }

    public static void sleep(long timer) {
        try {
            TimeUnit.MILLISECONDS.sleep(timer);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T swap(T t, MethodInterceptor interceptor) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(t.getClass());
        enhancer.setCallback(interceptor);
        return (T) enhancer.create();
    }

    public static <T> T swapBeanSetAfter(T bean, BiConsumer<T, Method> consumer) {
        T ret = swap(bean, (o, method, objects, methodProxy) -> {
            Object newRet = methodProxy.invokeSuper(o, objects);
            if ( method.getName().startsWith("set") )
                consumer.accept((T) o, method);
            return newRet;
        });
        return ret;
    }

}
